package com.nineclock.auth.aspect;

import com.nineclock.auth.dto.NcOauthTokenDTO;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.entity.IntegrationAuthenticationHolder;
import com.nineclock.auth.entity.UserHolder;
import com.nineclock.common.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
@Aspect
public class AuthTokenAspect {

    @Autowired
    HttpServletRequest request;

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

//        前置增强
//        从请求中获取请求参数,封装对象
        String authType = request.getParameter("auth_type");
        IntegrationAuthenticationEntity entity=new IntegrationAuthenticationEntity();
        entity.setAuthType(authType);
        entity.setAuthParameters(request.getParameterMap());
//       存储到当前线程中
        IntegrationAuthenticationHolder.set(entity);

        try {
//            调用原始方法s
            Object objResult = joinPoint.proceed();
            Result result=null;
//            后置增强(改变返回值)
            ResponseEntity<OAuth2AccessToken> responseEntity= (ResponseEntity<OAuth2AccessToken>) objResult;
            if (responseEntity.getStatusCode().is2xxSuccessful()){
                OAuth2AccessToken body = responseEntity.getBody();
                NcOauthTokenDTO oauthTokenDTO=new NcOauthTokenDTO();

                oauthTokenDTO.setUser(UserHolder.get());
                oauthTokenDTO.setOauth2AccessToken(body);

                result=Result.success();
            }else {
                result=Result.errorCodeMessage(401,"获取token失败");
            }


            return  ResponseEntity.ok(result);
        } finally {
//            最终增强
            IntegrationAuthenticationHolder.remove();
            UserHolder.remove();
        }

//        异常增强被删掉了，添加认证异常统一处理结果
    }
}
